﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace X23.Util.LinqUtil
{
    /// <summary>
    /// 分页
    /// </summary>
    public static class LinqPageUtil
    {
        /// <summary>
        /// 分页
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="pages">页数</param>
        /// <param name="rows">行数 默认10行</param>
        /// <returns></returns>
        public static PageData<T> ToPageList<T>(this IQueryable<T> query, int pages, int rows = 10) where T : class
        {
            if (pages < 1 || rows < 1)
            {
                throw new Exception($"页数行数不正确：pages={pages},rows={rows}");
            }
            var total = query.Count();
            var data = query.Skip((pages - 1) * rows).Take(rows).ToList();
            var isHasNext = pages * rows < total;
            var result = new PageData<T>
            {
                Total = total,
                CurrentPage = pages,
                Rows = rows,
                IsHasNext = isHasNext,
                Data = data
            };
            return result;
        }
    }
    /// <summary>
    /// 分页dto
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class PageData<T> 
    {
        /// <summary>
        /// 总计
        /// </summary>
        public int Total { get; set; }
        /// <summary>
        /// 当前页
        /// </summary>
        public int CurrentPage { get; set; }
        /// <summary>
        /// 行数
        /// </summary>
        public int Rows { get; set; }
        /// <summary>
        /// 是否有下一页
        /// </summary>
        public bool IsHasNext { get; set; }
        /// <summary>
        /// 数据
        /// </summary>
        public List<T> Data { get; set; }
    }
}
